﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Text.RegularExpressions;

namespace Mojito.Utils
{
    public static class StringUtil
    {

        #region 摘要

        /// <summary>
        ///  MD5 摘要
        ///  密码摘要后皆为小写
        /// </summary>
        /// <param name="message">明文</param>
        /// <returns>密文(小写)</returns>
        public static string MD5Encrypt(string message)
        {
            string result = "";
            if (!string.IsNullOrWhiteSpace(message))
            {
                // 将密码转换为 byte 数组
                var bytes = Encoding.UTF8.GetBytes(message);
                // 数组 Hash 转换
                bytes = new MD5CryptoServiceProvider().ComputeHash(bytes);
                // 将 byte 逐字转换为十六进制的字符组合成密文
                foreach (var b in bytes)
                {
                    result += b.ToString("x").PadLeft(2, '0');
                }
                return result.ToLower();
            }
            return result;
        }

        #endregion

        #region 判断

        /// <summary>
        ///  密码强度
        /// </summary>
        /// <param name="password">密码</param>
        /// <returns>
        ///     强度等级 0-4, 数值越高越强
        /// </returns>
        public static int PasswordStrength(string password)
        {
            // 强度值
            int strength = 0;
            // 空字符串强度值为0
            if (string.IsNullOrWhiteSpace(password)) return strength;
            // 字符统计
            int iNum = 0, iULtt = 0, iLLtt = 0, iSym = 0;
            foreach (char c in password)
            {
                if (c >= '0' && c <= '9') iNum++;
                else if (c >= 'a' && c <= 'z') iLLtt++;
                else if (c >= 'A' && c <= 'Z') iULtt++;
                else iSym++;
            }
            strength += iLLtt > 0 ? 1 : 0;
            strength += iULtt > 0 ? 1 : 0;
            strength += iNum > 0 ? 1 : 0;
            strength += iSym > 0 ? 1 : 0;
            return strength;
        }

        #endregion

        #region 编码

        //private static string UrlEncode(string temp, Encoding encoding)
        //{
        //    StringBuilder stringBuilder = new StringBuilder();
        //    for (int i = 0; i < temp.Length; i++)
        //    {
        //        string t = temp[i].ToString();
        //        string k = HttpUtility.UrlEncode(t, encoding);
        //        if (t == k)
        //        {
        //            stringBuilder.Append(t);
        //        }
        //        else
        //        {
        //            stringBuilder.Append(k.ToUpper());
        //        }
        //    }
        //    return stringBuilder.ToString();
        //}
        //public static string URLEncode(string text)
        //{
        //    return HttpUtility.UrlEncode(text, Encoding.Default);
        //}
        //public static string URLDecode(string text)
        //{
        //    return ""; //HttpUtility.UrlDecode(text, Encoding.Default);
        //}

        public static string Base64Encode(string input)
        {
            return Base64Encode(input, new UTF8Encoding());
        }
        public static string Base64Encode(string input, Encoding encode)
        {
            return Convert.ToBase64String(encode.GetBytes(input));
        }
        public static string Base64Decode(string input)
        {
            return Base64Decode(input, new UTF8Encoding());
        }
        public static string Base64Decode(string input, Encoding encode)
        {
            return encode.GetString(Convert.FromBase64String(input));
        }

        #endregion

        #region 转换

        /// <summary>
        ///  将字段转换为 Url 格式的字符串
        /// </summary>
        /// <param name="param"></param>
        /// <returns></returns>
        public static string ToUrlString(this IDictionary<string, object> param)
        {
            if (param == null || param.Count == 0)
                return "";
            var kv = param.Select(s => $"{s.Key}={s.Value.ToString()}");
            return string.Join("&", kv);
        }

        /// <summary>
        ///  将字典转完成 XML格式的 字符串
        /// </summary>
        /// <param name="param"></param>
        /// <returns></returns>
        public static string ToXml(IDictionary<string, string> param)
        {
            StringBuilder sb = new StringBuilder();
            sb.Append("<xml>");
            foreach (string k in param.Keys)
            {
                string v = (string)param[k];
                if (k != "notify_url") //Regex.IsMatch(v, @"^[0-9.]$")
                {
                    sb.Append("<" + k + ">" + v + "</" + k + ">");
                }
                else
                {
                    sb.Append("<" + k + "><![CDATA[" + v + "]]></" + k + ">");
                }

            }
            sb.Append("</xml>");
            return sb.ToString();
        }

        #endregion

        #region 加工

        ///   <summary> 
        ///   将指定字符串按指定长度进行截取并加上指定的后缀
        ///   </summary> 
        ///   <param   name= "oldStr "> 需要截断的字符串 </param> 
        ///   <param   name= "maxLength "> 字符串的最大长度 </param> 
        ///   <param   name= "endWith "> 超过长度的后缀 </param> 
        ///   <returns> 如果超过长度，返回截断后的新字符串加上后缀，否则，返回原字符串 </returns> 
        public static string StringTruncat(string oldStr, int maxLength, string endWith)
        {
            //判断原字符串是否为空
            if (string.IsNullOrEmpty(oldStr))
                return oldStr + endWith;


            //返回字符串的长度必须大于1
            if (maxLength < 1)
                throw new Exception("返回的字符串长度必须大于[0] ");


            //判断原字符串是否大于最大长度
            if (oldStr.Length > maxLength)
            {
                //截取原字符串
                string strTmp = oldStr.Substring(0, maxLength);


                //判断后缀是否为空
                if (string.IsNullOrEmpty(endWith))
                    return strTmp;
                else
                    return strTmp + endWith;
            }
            return oldStr;
        }

        /// <summary>
        /// 去除HTML格式
        /// </summary>
        /// <param name="Htmlstring"></param>
        /// <returns></returns>
        public static string RemoveHtmlString(string Htmlstring)//将HTML去除
        {
            //string[,] map = new string[,] {
            //    { @"<script[^>]*?>.*?</script>", "" },
            //    { @"<(.[^>]*)>", "" },
            //    { @"([\r\n])[\s]+", "" },
            //    { @"-->", "" },
            //    { @"<!--.*", "" },
            //    { @"&(quot|#34);", "" },
            //    { @"&(ldquo|#34);", "" },
            //    { @"&(rdquo|#34);", "" },
            //    { @"&(mdash|#45);", "" },
            //    { @"&(amp|#38);", "" },
            //    { @"&(lt|#60);", "" },
            //    { @"&(gt|#62);", "" },
            //    { @"&(nbsp|#160);", "" },
            //    { @"&(iexcl|#161);", "" },
            //    { @"&(cent|#162);", "" },
            //};

            //删除脚本
            Htmlstring = Regex.Replace(Htmlstring, @"<script[^>]*?>.*?</script>", "", RegexOptions.IgnoreCase);
            //删除HTML
            Htmlstring = Regex.Replace(Htmlstring, @"<(.[^>]*)>", "", RegexOptions.IgnoreCase);
            Htmlstring = Regex.Replace(Htmlstring, @"([\r\n])[\s]+", "", RegexOptions.IgnoreCase);
            Htmlstring = Regex.Replace(Htmlstring, @"-->", "", RegexOptions.IgnoreCase);
            Htmlstring = Regex.Replace(Htmlstring, @"<!--.*", "", RegexOptions.IgnoreCase);
            //Htmlstring = Regex.Replace(Htmlstring,@"<A>.*</A>","");
            //Htmlstring = Regex.Replace(Htmlstring,@"<[a-zA-Z]*=\.[a-zA-Z]*\?[a-zA-Z]+=\d&\w=%[a-zA-Z]*|[A-Z0-9]","");
            Htmlstring = Regex.Replace(Htmlstring, @"&(quot|#34);", "\"", RegexOptions.IgnoreCase);
            Htmlstring = Regex.Replace(Htmlstring, @"&(ldquo|#34);", "\"", RegexOptions.IgnoreCase);
            Htmlstring = Regex.Replace(Htmlstring, @"&(rdquo|#34);", "\"", RegexOptions.IgnoreCase);
            Htmlstring = Regex.Replace(Htmlstring, @"&(mdash|#45);", "-", RegexOptions.IgnoreCase);
            Htmlstring = Regex.Replace(Htmlstring, @"&(amp|#38);", "&", RegexOptions.IgnoreCase);
            Htmlstring = Regex.Replace(Htmlstring, @"&(lt|#60);", "<", RegexOptions.IgnoreCase);
            Htmlstring = Regex.Replace(Htmlstring, @"&(gt|#62);", ">", RegexOptions.IgnoreCase);
            Htmlstring = Regex.Replace(Htmlstring, @"&(nbsp|#160);", " ", RegexOptions.IgnoreCase);
            Htmlstring = Regex.Replace(Htmlstring, @"&(iexcl|#161);", "\xa1", RegexOptions.IgnoreCase);
            Htmlstring = Regex.Replace(Htmlstring, @"&(cent|#162);", "\xa2", RegexOptions.IgnoreCase);
            Htmlstring = Regex.Replace(Htmlstring, @"&(pound|#163);", "\xa3", RegexOptions.IgnoreCase);
            Htmlstring = Regex.Replace(Htmlstring, @"&(copy|#169);", "\xa9", RegexOptions.IgnoreCase);
            Htmlstring = Regex.Replace(Htmlstring, @"&#(\d+);", "", RegexOptions.IgnoreCase);

            // 删除特殊字符
            Htmlstring.Replace("<", "");
            Htmlstring.Replace(">", "");
            Htmlstring.Replace("\r\n", "");
            //Htmlstring=HttpContext.Current.Server.HtmlEncode(Htmlstring).Trim();

            return Htmlstring;

        }

        #endregion

        #region 提取

        /// <summary>
        ///  获取文件后缀名
        /// </summary>
        /// <param name="filename">文件名</param>
        /// <returns></returns>
        public static string GetExtension(string filename)
        {
            var index = filename.LastIndexOf('.');
            return index != -1 ?
                filename.Substring(index) : "";

            // return Path.GetExtension(MapPathFile(FileName));
        }

        #endregion
    }
}
